import { AccountRoleEntity } from './../../entities/account.role.entity';
import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getManager, EntityManager } from 'typeorm';
import { MutationRes } from 'src/modules/shared/vo/mutation.res';
import { CreateAccountRoleInput } from '../../resolvers/accout-role/dto/create.account.role.input';

@Injectable()
export class AccountRoleService {
  constructor (
    @InjectRepository(AccountRoleEntity)
    private readonly accountRoleRepository: Repository<AccountRoleEntity>,
  ) { }
  
  async createAccountRole(createAccountRoleInput: CreateAccountRoleInput): Promise<MutationRes> {
    const { accountId, roleIdList } = createAccountRoleInput;
    return getManager()
      .transaction(async (entityManager: EntityManager) => {
        await entityManager.delete(AccountRoleEntity, { accountId: Number(accountId) });
        for (const item of roleIdList) {
          await entityManager.save(AccountRoleEntity, { accountId, roleId: Number(item) });
        }
      }).then(async () => {
        return {
          code: 0,
          message: '成功',
        };
      }).catch((e) => {
        Logger.error('账号分配角色错误', e);
        throw new HttpException('账号分配角色错误', HttpStatus.OK);
      });
  }
}
